package com.qut.graduate.busrtquery.presenter;

import android.os.Handler;
import android.os.Message;

import com.bumptech.glide.Glide;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.ui.user.UserCenterActivity;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.photoselect.FileUtils;
import com.qut.graduate.busrtquery.utils.store.SPUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * @Author WLL
 * @Time: 2019/3/31 17:39
 */
public class UserCenterPresenter {
    private static final String TAG = "UserCenterPresenter";
    private MyHandler myHandler;
    private SPUtils mSPUtils;
    private UserCenterActivity userCenterActivity;

    public UserCenterPresenter(UserCenterActivity userCenterActivity) {
        this.userCenterActivity = userCenterActivity;
        mSPUtils = SPUtils.getInstance(userCenterActivity.getApplicationContext());
        if (null == myHandler) myHandler = new MyHandler(userCenterActivity);
    }

    private static class MyHandler extends Handler {

        private WeakReference<UserCenterActivity> weakReference;

        public MyHandler(UserCenterActivity userCenterActivity) {
            weakReference = new WeakReference<>(userCenterActivity);
        }

        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            UserCenterActivity userCenterActivity = weakReference.get();
            switch (msg.what) {
                case BRTQConstant.BMOB_IMAGE_HEADER_SAVE_PATH:
                    userCenterActivity.setSavePath((String) msg.obj);
                    LogUtils.d("----用户中心Presenter  bomb图片地址:" + msg.obj, this.getClass());
                    Glide.with(userCenterActivity).load(msg.obj).into(userCenterActivity.getmUserAnimImage());
                    break;
                case BRTQConstant.BMOB_IMAGE_BG_SAVE_PATH:
                    userCenterActivity.setSavePath((String) msg.obj);
                    LogUtils.d("----用户中心Presenter  bomb图片地址:" + msg.obj, this.getClass());
                    Glide.with(userCenterActivity).load(msg.obj).into(userCenterActivity.getmUserHeaderBg());
                    break;
            }
        }
    }

    /**
     * 上传图片
     *
     * @param imagePath
     * @param type
     */
    public void uploadPic(final String imagePath, final int type) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                final BmobFile image = new BmobFile(new File(imagePath));
                final String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
                image.uploadblock(new UploadFileListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            String imageUrl = image.getFileUrl();
                            User user = BmobUser.getCurrentUser(User.class);
                            if (type == BRTQConstant.BMOB_IMAGE_HEADER) {
                                user.setHeadImg(image);
                                user.setHeadImgName(imageName);
                            } else if (type == BRTQConstant.BMOB_IMAGE_BG) {
                                user.setBgImg(image);
                                user.setBgImgName(imageName);
                            }
                            user.update(user.getObjectId(), new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        LogUtils.d("----用户中心Presenter  图片上传成功", this.getClass());
                                        ToastColorfulUtils.success("图片上传成功");
                                    } else {
                                        LogUtils.d("----用户中心Presenter  图片上传失败" + String.valueOf(e), this.getClass());
                                        ToastColorfulUtils.error("图片上传失败");
                                    }
                                }
                            });
                            LogUtils.d("----用户中心Presenter  图片上传成功", this.getClass());
                        } else {
                            LogUtils.d("----用户中心Presenter  图片上传失败", this.getClass());
                        }
                    }
                });
            }
        });
        thread.start();
    }

    public void downloadFile(final int type) {
        BmobFile file = null;
        if (type == BRTQConstant.BMOB_IMAGE_HEADER) {
            file = BmobUser.getCurrentUser(User.class).getHeadImg();
        }
        if (type == BRTQConstant.BMOB_IMAGE_BG) {
            file = BmobUser.getCurrentUser(User.class).getBgImg();
        }
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        if (file != null) {
            FileUtils.createOrExistsDir(BRTQConstant.USER_DOWNLOAD_DIR);
            final File saveFile = new File(BRTQConstant.USER_DOWNLOAD_DIR, file.getFilename());
            file.download(saveFile, new DownloadFileListener() {
                @Override
                public void onStart() {
                    LogUtils.d("----用户中心Presenter  开始下载...", this.getClass());
                }

                @Override
                public void done(String savePath, BmobException e) {
                    if (e == null) {
                        ToastColorfulUtils.success("下载成功");
                        LogUtils.d("----用户中心Presenter  下载成功,保存路径:" + savePath, this.getClass());
                        String pictureName = savePath.substring(savePath.lastIndexOf("/") + 1);
                        Message message = Message.obtain();
                        if (type == BRTQConstant.BMOB_IMAGE_HEADER) {
                            message.what = BRTQConstant.BMOB_IMAGE_HEADER_SAVE_PATH;
                            mSPUtils.putString(userCenterActivity.getString(R.string.preference_user_header), pictureName);
                            mSPUtils.putString(userCenterActivity.getString(R.string.preference_user_header_path), savePath);
                        }
                        if (type == BRTQConstant.BMOB_IMAGE_BG) {
                            message.what = BRTQConstant.BMOB_IMAGE_BG_SAVE_PATH;
                            mSPUtils.putString(userCenterActivity.getString(R.string.preference_user_bg), pictureName);
                            mSPUtils.putString(userCenterActivity.getString(R.string.preference_user_bg_path), savePath);
                        }
                        message.obj = savePath;
                        myHandler.sendMessage(message);
                    } else {
                        ToastColorfulUtils.error("下载失败");
                        LogUtils.d("----用户中心Presenter  下载失败：" + e.getErrorCode() + "," + e.getMessage(), this.getClass());
                    }
                }

                @Override
                public void onProgress(Integer value, long newworkSpeed) {
                    LogUtils.d("----用户中心Presenter  下载进度：" + value + "," + newworkSpeed, this.getClass());
                }
            });
        }
    }

    public boolean bmobImageIsNull(final int type) {
        final boolean[] isNull = new boolean[1];
        isNull[0] = false;
        User user = BmobUser.getCurrentUser(User.class);
        String username = null;
        if (user != null) {
            username = user.getUsername();
        }
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("username", username);
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null && null != object) {
                    if (type == BRTQConstant.BMOB_IMAGE_HEADER) {
                        isNull[0] = object.get(0).getHeadImg() != null;
                    } else if (type == BRTQConstant.BMOB_IMAGE_BG) {
                        isNull[0] = object.get(0).getBgImg() != null;
                    }
                } else {
                    LogUtils.d("----用户中心Presenter  bmobImageIsNull异常：" + String.valueOf(e), this.getClass());
                    isNull[0] = false;
                }
            }
        });
        return isNull[0];
    }

    public boolean compareImageName(String imagePath, final int type) {
        final String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
        final boolean[] isSame = new boolean[1];
        isSame[0] = false;
        BmobQuery<User> query = new BmobQuery<User>();
        if (type == BRTQConstant.BMOB_IMAGE_HEADER) {
            query.addWhereEqualTo("headImgName", imageName);
        } else if (type == BRTQConstant.BMOB_IMAGE_BG) {
            query.addWhereEqualTo("bgImgName", imageName);
        }
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null && null != object) {
                    if (object.size() > 0) {
                        LogUtils.d("----用户中心Presenter  用户图片存在", this.getClass());
                        isSame[0] = true;
                    } else {
                        LogUtils.d("----用户中心Presenter  用户图片不存在", this.getClass());
                        isSame[0] = false;
                    }
                } else {
                    LogUtils.d("----用户中心Presenter  compareImageName异常:" + String.valueOf(e), this.getClass());
                    isSame[0] = false;
                }
            }
        });
        return isSame[0];
    }

}
